package com.zndroid.base.ui.impl;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;

import com.zndroid.base.callback.inner.mvp.IPresenter;
import com.zndroid.base.callback.inner.mvp.IView;

import java.lang.ref.WeakReference;

/**
 * BasePresenter support {@link Lifecycle}
 * @author lzy
 * @date 2021/3/4
 */
@SuppressWarnings("unused")
public abstract class BasePresenter<V extends IView> implements IPresenter<V>, DefaultLifecycleObserver {
    private WeakReference<V> viewReference;

    @Override
    public void attachView(V view) {
        viewReference = new WeakReference<V>(view);
    }

    @Override
    public void detachView() {
        if (null != viewReference) {
            viewReference.clear();
        }
    }

    @Override
    public V getV() {
        if (null != viewReference) {
            return viewReference.get();
        } else {
            throw new UnsupportedOperationException("pls call #attachView(V) at first.");
        }
    }

    /**
     * current 'View' is initialized and attached
     *
     * @return true or false
     * */
    protected boolean isAttached() {
        return (null != viewReference)
                && (null != viewReference.get());
    }

    /**
     * current 'View' operable
     *
     * @return true or false
     * */
    protected boolean isActivate() {
        if (isAttached()) {
            return !getV().isDied();
        } else {
            return false;
        }
    }

    @Override
    public void onCreate(@NonNull LifecycleOwner owner) {
        didOnCreate();
    }

    @Override
    public void onStart(@NonNull LifecycleOwner owner) {
        didOnStart();
    }

    @Override
    public void onResume(@NonNull LifecycleOwner owner) {
        didOnResume();
    }

    @Override
    public void onPause(@NonNull LifecycleOwner owner) {
        didOnPause();
    }

    @Override
    public void onStop(@NonNull LifecycleOwner owner) {
        didOnStop();
    }

    @Override
    public void onDestroy(@NonNull LifecycleOwner owner) {
        didOnDestroy();
    }

    public void didOnCreate() {}

    protected void didOnStart() {}

    public void didOnResume() {}

    protected void didOnPause() {}

    protected void didOnStop() {}

    protected void didOnDestroy() {}

    protected void didOnBackPressed() {}

    protected Bundle getBundleArgs() {
        if (isAttached()) {
           return getV().getBundleArgs();
        }

        return null;
    }

    protected Intent currentIntent() {
        if (isAttached()) {
            return getV().currentIntent();
        }

        return null;
    }
}
